//
//  BMHCashOutAuthorizeViewController.m
//  BMHVideoMain
//
//  Created by 陈宪栋 on 2017/7/13.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "BMHCashOutAuthorizeViewController.h"
#import "BMHCashOutAuthorizeTableViewCell.h"
#import "BMHCashOutAuthorizeFooterView.h"
#import "BMHFeedbackController.h"
#import "BMHCashOutAuthorizeWebViewController.h"
#import <ReactiveCocoa.h>
#import "XLHTTPSessionManager+CashOut.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLUserInfoView.h"
#import <IQKeyboardManager.h>

@interface BMHCashOutAuthorizeViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,XLUserInfoViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phoneNumber;
@property (nonatomic, copy) NSString *bankNumber;
@property (nonatomic, copy) NSString *bankName;
@property (nonatomic, copy) NSString *identityNumber;
@property (nonatomic, weak) UITextField *editingTextField;

//弹窗容器
@property (nonatomic, strong) UIWindow *window;

@property (nonatomic, strong) NSArray *cellArray;
@end

@implementation BMHCashOutAuthorizeViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"实名认证";
    [[UITextField appearance] setTintColor:[UIColor darkGrayColor]];
    [self showBackButton:NULL];
    [self setupView];
}

- (void)setupView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    BMHCashOutAuthorizeFooterView *footerView = [[BMHCashOutAuthorizeFooterView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    [footerView.contactButton addTarget:self action:@selector(contactAction:) forControlEvents:UIControlEventTouchUpInside];
    [footerView.commitButton addTarget:self action:@selector(commitAction:) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footerView;
    
    BMHCashOutAuthorizeTableViewCell *cell1 = [[BMHCashOutAuthorizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell1.textField.attributedPlaceholder = [[NSMutableAttributedString alloc]initWithString:@"请输入真实姓名" attributes:@{NSForegroundColorAttributeName:kLightGrayColor}];
    cell1.textField.keyboardAppearance = UIKeyboardAppearanceLight;
    cell1.textField.keyboardType = UIKeyboardTypeDefault;
    cell1.textField.tintColor = [UIColor darkGrayColor];
    cell1.textField.delegate = self;
    cell1.textField.tag = 1001;
    cell1.titleLabel.text = @"姓名";
    [cell1.textField becomeFirstResponder];
    cell1.textField.frame = CGRectMake(52, 0, ScreenWidth - 50, 45);
    BMHCashOutAuthorizeTableViewCell *cell2 = [[BMHCashOutAuthorizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell2.textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入身份证号" attributes:@{NSForegroundColorAttributeName:kLightGrayColor}];
    cell2.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cell2.textField.delegate = self;
    cell2.textField.tintColor = [UIColor darkGrayColor];
    cell2.textField.keyboardAppearance = UIKeyboardAppearanceLight;
    cell2.textField.tag = 1002;
    cell2.titleLabel.text = @"身份证";
    cell2.textField.frame = CGRectMake(70, 0, ScreenWidth - 70,45);
    BMHCashOutAuthorizeTableViewCell *cell3 = [[BMHCashOutAuthorizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell3.textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName:kLightGrayColor}];
    cell3.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cell3.textField.delegate = self;
    cell3.textField.tintColor = [UIColor darkGrayColor];
    cell3.textField.keyboardAppearance = UIKeyboardAppearanceLight;
    cell3.textField.tag = 1003;
    cell3.titleLabel.text = @"手机";
    cell3.textField.frame = CGRectMake(52, 0, ScreenWidth - 50, 45);
    BMHCashOutAuthorizeTableViewCell *cell4 = [[BMHCashOutAuthorizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell4.textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入开户行" attributes:@{NSForegroundColorAttributeName:kLightGrayColor}];
    cell4.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cell4.textField.delegate = self;
    cell4.textField.tintColor = [UIColor darkGrayColor];
    cell4.textField.keyboardAppearance = UIKeyboardAppearanceLight;
    cell4.textField.tag = 1004;
    cell4.titleLabel.text = @"开户行";
    cell4.textField.frame = CGRectMake(70, 0, ScreenWidth - 70, 45);
    BMHCashOutAuthorizeTableViewCell *cell5 = [[BMHCashOutAuthorizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell5.textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入银行卡号" attributes:@{NSForegroundColorAttributeName:kLightGrayColor}];
    cell5.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cell5.textField.delegate = self;
    cell5.textField.tintColor = [UIColor darkGrayColor];
    cell5.textField.keyboardAppearance = UIKeyboardAppearanceLight;
    cell5.textField.tag = 1005;
    cell5.titleLabel.text = @"银行卡号";
    cell5.textField.frame = CGRectMake(88, 0, ScreenWidth - 90, 45);
    self.cellArray = @[@[cell1], @[cell2], @[cell3], @[cell4, cell5]];
}

- (void)bindData {
    
}

#pragma mark - Action
- (void)contactAction:(id)sender {
    BMHFeedbackController *vc = [[BMHFeedbackController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)commitAction:(id)sender {
    BMHLog(@"姓名：%@", _name);
    BMHLog(@"手机号：%@", _phoneNumber);
    BMHLog(@"银行卡号：%@", _bankNumber);
    BMHLog(@"开户银行：%@", _bankName);
    BMHLog(@"身份证号：%@", _identityNumber);
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    
    NSString *nameRegex = @"^[\u4E00-\u9FA5A-Za-z]{2,16}";
    NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nameRegex];
    if ([namePredicate evaluateWithObject:_name] == NO) {
        [MBProgressHUD showContent:@"请输入正确的姓名" toView:self.view];
        return;
    }
    NSString *phoneRegex = @"^1[3-9]\\d{9}$";
    NSPredicate *phonePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    if ([phonePredicate evaluateWithObject:_phoneNumber] == NO) {
        [MBProgressHUD showContent:@"请输入正确的手机号" toView:self.view];
        return;
    }
    if ([self checkCardNo:_bankNumber] == NO) {
        [MBProgressHUD showContent:@"请输入正确的银行卡号" toView:self.view];
        return;
    }
    if ([namePredicate evaluateWithObject:_bankName] == NO) {
        [MBProgressHUD showContent:@"请输入正确的开户银行" toView:self.view];
        return;
    }
    if ([self validateIDCardNumber:_identityNumber] == NO) {
        [MBProgressHUD showContent:@"请输入正确的身份证号" toView:self.view];
        return;
    }
    
    //确认信息
    [self setAlertWithInfo];
    
}


#pragma mark    - - - 设置确认信息 - - -
- (void)setAlertWithInfo
{
    //设置容器显示
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    self.window.backgroundColor = [UIColor clearColor];
    
    self.window.windowLevel = UIWindowLevelAlert + 1;
    
    //显示弹窗内容
    XLUserInfoView *userInfo = [[XLUserInfoView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    userInfo.delegate = self;
    
    //获取数据
    userInfo.name = _name;
    
    userInfo.identifierCard = _identityNumber;
    
    userInfo.iphoneNum = _phoneNumber;
    
    userInfo.bank = _bankName;
    
    [self.window addSubview:userInfo];
    
    [self.window makeKeyAndVisible];
}

#pragma mark    - - - XLUserInfoDelegate - - -
- (void)clickUserInfo:(BOOL)isCommit
{
    if (isCommit) {
        [MBProgressHUD showMessage:@"正在提交..." toView:self.view];
        [[[XLHTTPSessionManager sharedManager] signWithUserId:[[XLAccountManager shareInstance] model].Id name:_name mobile:_phoneNumber idNumber:_identityNumber bankName:_bankName bankNum:_bankNumber] subscribeNext:^(id x) {
            [MBProgressHUD hideHUDForView:self.view];
            NSString *url = [x objectForKey:@"url"];
            BMHCashOutAuthorizeWebViewController *vc = [[BMHCashOutAuthorizeWebViewController alloc] init];
            vc.url = url;
            vc.navigationItem.title = @"授权确认";
            [self.navigationController pushViewController:vc animated:YES];
            
            [self.window resignKeyWindow];
            
            self.window = nil;
            
            
        } error:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showContent:error.userInfo[NSLocalizedDescriptionKey] toView:self.view];
            
            [self.window resignKeyWindow];
            
            self.window = nil;
            
        }];
        
        
    }else{
        
        //这样是让上传菊花旋转的时候 提示框仍存在
        [self.window resignKeyWindow];
        
        self.window = nil;
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section < 3 ? 1 : 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BMHCashOutAuthorizeTableViewCell *cell = self.cellArray[indexPath.section][indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    switch (textField.tag) {
            case 1001: {
                self.name = textField.text;
            }
            break;
            case 1002: {
                self.identityNumber = textField.text;
            }
            break;
            case 1003: {
                self.phoneNumber = textField.text;
            }
            break;
            case 1004: {
                self.bankName = textField.text;
            }
            break;
            case 1005: {
                self.bankNumber = textField.text;
            }
            break;
            
        default:
            break;
    }
}

#pragma mark - private
//银行卡校验
- (BOOL)checkCardNo:(NSString *)cardNo{
    int oddsum = 0;    //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    if (cardNoLength < 2) return NO;
    int lastNum = [[cardNo substringFromIndex:cardNoLength - 1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength - 1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1,1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) ==0)
    return YES;
    else
    return NO;
}

// 身份证验证
- (BOOL)validateIDCardNumber:(NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length = 0;
    
    if (!value) {
        return NO;
    }
    else {
        length = (int)value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12",@"13",@"14",@"15",@"21",@"22",@"23",@"31",@"32",@"33",@"34",@"35",@"36",@"37",@"41",@"42",@"43",@"44",@"45",@"46",@"50",@"51",@"52",@"53",@"54",@"61",@"62",@"63",@"64",@"65",@"71",@"81",@"82",@"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    
    BOOL areaFlag =NO;
    
    for (NSString *areaCode in areasArray) {
        
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    int year =0;
    switch (length) {
            case 15:{
                year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
                if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                    regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                            options:NSRegularExpressionCaseInsensitive
                                                                              error:nil];//测试出生日期的合法性
                }else {
                    regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                            options:NSRegularExpressionCaseInsensitive
                                                                              error:nil];//测试出生日期的合法性
                }
                numberofMatch = [regularExpression numberOfMatchesInString:value
                                                                   options:NSMatchingReportProgress
                                                                     range:NSMakeRange(0, value.length)];
                
                if(numberofMatch >0) {
                    return YES;
                }else {
                    return NO;
                }
            }
            case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                int Y = S %11;
                
                NSString *M =@"F";
                
                NSString *JYM =@"10X98765432";
                
                M = [JYM substringWithRange:NSMakeRange(Y,1)];//判断校验位
                
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
            }else {
                
                return NO;
            }
        default:
            return NO;
    }
}
@end
